import psutil
import platform
import socket
import datetime
import time
from collections import deque
import os
import json
from typing import Dict, List, Any

# 创建历史数据存储（最近15分钟的数据，每5秒一个点，共180个点）
class SystemMonitor:
    _instance = None
    # 单例模式
    def __new__(cls):
        if cls._instance is None:
            cls._instance = super(SystemMonitor, cls).__new__(cls)
            # 初始化历史数据存储
            cls._instance.cpu_history = deque(maxlen=180)
            cls._instance.memory_history = deque(maxlen=180)
            cls._instance.last_update_time = 0
            # 初始添加一些0值，以便图表显示
            for _ in range(180):
                cls._instance.cpu_history.append(0)
                cls._instance.memory_history.append(0)
        return cls._instance
    
    def get_system_info(self) -> Dict[str, str]:
        """获取系统基本信息"""
        boot_time = datetime.datetime.fromtimestamp(psutil.boot_time())
        uptime = datetime.datetime.now() - boot_time
        
        # 计算运行时间
        days, remainder = divmod(uptime.total_seconds(), 86400)
        hours, remainder = divmod(remainder, 3600)
        minutes, seconds = divmod(remainder, 60)
        
        uptime_str = f"{int(days)}天{int(hours)}小时{int(minutes)}分钟"
        boot_time_str = boot_time.strftime("%Y-%m-%d %H:%M:%S")
        
        return {
            "hostname": socket.gethostname(),
            "os_name": platform.system(),
            "os_version": platform.version(),
            "uptime": uptime_str,
            "boot_time": boot_time_str
        }
    
    def get_resource_usage(self) -> Dict[str, Any]:
        """获取资源使用情况"""
        current_time = time.time()
        # 每5秒更新一次历史数据
        if current_time - self.last_update_time >= 5:
            self.last_update_time = current_time
            # 获取CPU使用率
            cpu_percent = psutil.cpu_percent(interval=1)
            # 获取内存使用率
            memory = psutil.virtual_memory()
            memory_percent = memory.percent
            
            # 更新历史数据
            self.cpu_history.append(cpu_percent)
            self.memory_history.append(memory_percent)
        else:
            # 获取CPU使用率（不等待）
            cpu_percent = psutil.cpu_percent(interval=None)
            # 获取内存使用率
            memory = psutil.virtual_memory()
            memory_percent = memory.percent
        
        # 获取磁盘使用情况
        disk = psutil.disk_usage("/")
        
        # 转换为易读的格式
        def human_readable_size(size_bytes):
            """将字节数转换为易读的格式"""
            for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
                if size_bytes < 1024.0:
                    return f"{size_bytes:.2f} {unit}"
                size_bytes /= 1024.0
            return f"{size_bytes:.2f} PB"
        
        return {
            "cpu_percent": cpu_percent,
            "memory_percent": memory_percent,
            "memory_used": human_readable_size(memory.used),
            "memory_total": human_readable_size(memory.total),
            "disk_percent": disk.percent,
            "disk_used": human_readable_size(disk.used),
            "disk_total": human_readable_size(disk.total),
            "cpu_history": list(self.cpu_history),
            "memory_history": list(self.memory_history)
        }
    
    def get_all_info(self) -> Dict[str, Dict]:
        """获取所有系统信息"""
        return {
            "system_info": self.get_system_info(),
            "resource_usage": self.get_resource_usage()
        } 